package com.example.smartcs.service.impl;

import com.example.smartcs.model.ChatRequest;
import com.example.smartcs.model.ChatResponse;
import com.example.smartcs.service.CustomerServiceAgent;
import dev.langchain4j.model.chat.ChatLanguageModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class CustomerServiceAgentImpl implements CustomerServiceAgent {

    private final ChatLanguageModel deepseekModel;
    private final ChatLanguageModel qwenModel;
    private final Map<String, String> conversationHistory = new HashMap<>();

    public CustomerServiceAgentImpl(
            @Qualifier("deepseekModel") ChatLanguageModel deepseekModel,
            @Qualifier("qwenModel") ChatLanguageModel qwenModel) {
        this.deepseekModel = deepseekModel;
        this.qwenModel = qwenModel;
    }

    @Override
    public ChatResponse processRequest(ChatRequest request) {
        String sessionId = request.getSessionId();
        if (sessionId == null || sessionId.isEmpty()) {
            sessionId = UUID.randomUUID().toString();
        }

        // 获取历史记录或创建新的
        String history = conversationHistory.getOrDefault(sessionId, "");
        
        // 构建系统角色提示词
        String systemPrompt = "你是一个专业、友好的客服代表。请基于以下对话历史和用户问题，提供清晰、准确和有帮助的回答。" +
                "如果你不确定答案，请诚实地说明你不知道而不是编造信息。" +
                "以友好、专业的口吻回答，并确保回答简洁明了。\n\n";
        
        // 更新对话历史
        history += "\n用户: " + request.getMessage();
        
        // 构建prompt
        String prompt = systemPrompt + "对话历史:\n" + history + "\n\n请回答用户的问题。";
        
        String modelType = request.getModelType();
        if (modelType == null || modelType.isEmpty()) {
            modelType = "deepseek"; // 默认使用DeepSeek
        }
        
        String response;
        try {
            if ("qwen".equalsIgnoreCase(modelType)) {
                response = qwenModel.generate(prompt);
            } else {
                response = deepseekModel.generate(prompt);
            }
            
            // 更新对话历史
            history += "\n助手: " + response;
            conversationHistory.put(sessionId, history);
            
            return ChatResponse.builder()
                    .sessionId(sessionId)
                    .message(response)
                    .modelType(modelType)
                    .timestamp(System.currentTimeMillis())
                    .build();
            
        } catch (Exception e) {
            log.error("请求大模型API失败", e);
            return ChatResponse.builder()
                    .sessionId(sessionId)
                    .message("抱歉，服务暂时不可用，请稍后再试。")
                    .modelType(modelType)
                    .timestamp(System.currentTimeMillis())
                    .build();
        }
    }
} 